package vip.george.p0001;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

public class P1 {

    /**
     * 方法1： 暴力解法
     * 遍历数组
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }


    /**
     * 方法2： 哈希表+差值检验法
     */
    public int[] twoSum1(int[] nums, int target) {
        int len = nums.length;
        //哈希表<key是元素具体值，value是下标>
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            int current = nums[i];
            int diff = target - current;
            //检验哈希表中是否包含这个差值
            if(map.containsKey( diff)) {
                return new int[]{map.get(diff), i};
            } else {
                map.put(current, i);
            }
        }
        return new int[0];
    }

    public static void main(String[] args) {
        P1 p = new P1();
        System.out.println(Arrays.toString(p.twoSum1(new int[]{2, 7, 11, 15}, 9)));
    }
}
